﻿// <copyright file="HandleMediaElement.cs" company="Microsoft">
// Copyright (c) 2010 Microsoft All Rights Reserved
// </copyright>
// <author>Michael S. Scherotter</author>
// <email>mischero@microsoft.com</email>
// <date>2010-01-23</date>
// <summary>Web analytics service behavior class definition</summary>

namespace Microsoft.WebAnalytics.Behaviors.Handlers
{
    using System;
    using System.ComponentModel.Composition;
    using System.Windows;
    using System.Windows.Controls;
    using Microsoft.WebAnalytics;
    using Microsoft.WebAnalytics.Contracts;

    /// <summary>
    /// Track a MediaElement CurrentStateChanged, MediaOpened, and MediaFailed events
    /// </summary>
    [Tracker(typeof(MediaElement))]
    public class HandleMediaElement : ITrackHandler
    {
        #region Properties
        /// <summary>
        /// Gets or sets the event Logging method
        /// </summary>
        [Import("Log")]
        public Action<AnalyticsEvent> Log { get; set; }
        #endregion

        #region ITrackAction Members

        /// <summary>
        /// Track the media element events
        /// </summary>
        /// <param name="associatedObject">the associated object</param>
        /// <param name="analyticsEvent">the analytics event</param>
        /// <param name="eventArgs">the event arguments</param>
        public void Track(
            System.Windows.FrameworkElement associatedObject, 
            AnalyticsEvent analyticsEvent, 
            System.EventArgs eventArgs)
        {
            if (analyticsEvent == null)
            {
                throw new ArgumentNullException("analyticsEvent");
            }

            var mediaElement = associatedObject as MediaElement;

            switch (analyticsEvent.Name)
            {
                case "CurrentStateChanged":
#if SILVERLIGHT
                    analyticsEvent.ActionValue = mediaElement.CurrentState.ToString();
#endif
                    analyticsEvent.Value = System.Convert.ToInt32(Math.Floor(mediaElement.Position.TotalSeconds + 0.5));
                    analyticsEvent.MediaTimeCode = mediaElement.Position;
                    analyticsEvent.MediaSource = mediaElement.Source;
                    break;

                case "MediaOpened":
                    analyticsEvent.MediaSource = mediaElement.Source;
                    break;

                case "MediaFailed":
                    var exception = eventArgs as ExceptionRoutedEventArgs;
                    analyticsEvent.MediaSource = mediaElement.Source;
                    analyticsEvent.ActionValue = exception.ErrorException.Message;
                    break;
            }

            this.Log(analyticsEvent);
        }

        #endregion
    }
}
